package source.controller;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import source.events.UserInputManager;
import source.model.type.UnitType;
import source.view.MainScreen;
import java.awt.Color;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import javax.swing.JTabbedPane;

import source.Driver;
/**
 * PlayerKeyListener is a custom KeyListener designed to map custom key bindings
 * to standardized game events.  The string representations of the game events are
 * stored in an array of size 256.  The index of the array corrollates with the ascii
 * representation of a keyboard key.  PlayerKeyListener uses its UserInputManager
 * attribute to start the execution of the user event requests.  Pressing the PageUp
 * key restores all key bindings to defaults.  This is in case the user some how erases
 * any/all keybindings.
 * @author Joe
 *
 */
public class PlayerKeyListener extends KeyAdapter implements ChangeListener{

	private int pID;
	private String[] defaultKeyMap;
	private String[] keyMap;
	private UserInputManager uim;
	private boolean isActive;
	private static int nextpkl = 1;
	
	public PlayerKeyListener(String[] dkm, String[] ckm, int pid)
	{
		pID = pid;	
		defaultKeyMap = dkm;
		keyMap = ckm;
		isActive = false;
		if(pID != nextpkl)
		{
			isActive = true;
		}
	}
	
	public void setActiveFlag(boolean b)
	{
		//isActive = b;
	}
	/**
	 * @return String[]: the key map for this Listener 
	 */
	
	public String[] getKeyMap()
	{
		return this.keyMap;
	}
	
	/**
	 * sets the UserInputManager for this PlayerKeyListener
	 * 
	 * @param u: UserInputManager
	 * 
	 */
	
	public void setUserInputManager(UserInputManager u)
	{
		uim = u;
	}
	
	public boolean requestKeyChange(String id, int newKeyCode)
	{
		if(newKeyCode>255 || newKeyCode<0)
		{
			return false;
		}
		if(keyMap[newKeyCode].length()>0)
		{
			return false;
		}
		for(int k = 0; k<256; k++)
        {
      	  if(keyMap[k].equals(id))
      	  {
      		keyMap[k] = new String();
      		break;
      	  }
        }
        keyMap[newKeyCode] = id;
        CustomKeyFileManager.writeToFile(this);
		return true;
	}
	
	/**
	 * @return player id: int
	 */
	
	public int getPlayerID()
	{
		return this.pID;
	}
	
	//Assumption based on the fact that only JTabbedPane will be firing ChangeEvents
	
	/**
	 * @param evt: ChangeEvent
	 */
	
    public void stateChanged(ChangeEvent evt)
    {
        if(isActive)
        {
    	JTabbedPane pane = (JTabbedPane)evt.getSource();
        int sel = pane.getSelectedIndex();
        uim.setScreen(sel);
        }
    }
    
    /**
	 * @param e: KeyEvent
	 */
    
	public void keyPressed(KeyEvent e)
	{

			
		if(e.getKeyCode() < 256)
		{
			String key = keyMap[e.getKeyCode()];
			
			if(isActive && key.equals("EndTurn"))
			{
				isActive = false;			
			}
			else if(nextpkl == pID && key.equals("EndTurn"))
			{
				System.out.println("test");
				isActive = true;
				nextpkl = (nextpkl + 1)%Driver.numPlayers;
			}
			
			if(!isActive)
				return;
			
			if(key.equals("PrintKeyMap"))
			{
				String buffer = new String();
				for(int i = 0; i < 256; i++)
				{
					if(!keyMap[i].equals(new String()))
						buffer = buffer + keyMap[i] + ": " + KeyEvent.getKeyText(i) + "\n";
				}
				buffer = buffer.substring(0, buffer.length()-1);
				MainScreen.writeToConsole(buffer);
			}

			else if(key.equals("RevertToDefaultKeys"))
			{
				keyMap = defaultKeyMap;
				//MainScreen.writeToConsole("Player " + pID + "'s keys are restored to defaults");
			}
			
			else if(key.equals("MoveN"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Move North", Color.BLUE);
				uim.moveUnit(8);
			}

			else if(key.equals("MoveNE"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Move Northeast", Color.BLUE);
				uim.moveUnit(9);
			}

			else if(key.equals("MoveE"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Move East", Color.BLUE);
				uim.moveUnit(6);
			}
			
			else if(key.equals("MoveSE"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Move Southeast", Color.BLUE);
				uim.moveUnit(3);
			}

			else if(key.equals("MoveS"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Move South", Color.BLUE);
				uim.moveUnit(2);
			}

			else if(key.equals("MoveSW"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Move Southwest", Color.BLUE);
				uim.moveUnit(1);
			}
			
			else if(key.equals("MoveW"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Move West", Color.BLUE);
				uim.moveUnit(4);
			}

			else if(key.equals("MoveNW"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Move Northwest", Color.BLUE);
				uim.moveUnit(7);
			}
			
			else if(key.equals("BuildMelee"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Build Melee", Color.BLUE);
				uim.buildUnit(UnitType.MELEE);
			}

			else if(key.equals("BuildRanged"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Build Ranged", Color.BLUE);
				uim.buildUnit(UnitType.RANGED);
			}
			
			else if(key.equals("BuildExplorer"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Build Explorer", Color.BLUE);
				uim.buildUnit(UnitType.EXPLORER);
			}

			else if(key.equals("BuildColonist"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Build Colonist", Color.BLUE);
				uim.buildUnit(UnitType.COLONIST);
			}
			
			else if(key.equals("SelectNextUnit"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Select Next Unit", Color.BLUE);
				uim.selectNextUnit();
			}
			
			else if(key.equals("SelectNextBase"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Select Next Base", Color.BLUE);
				uim.selectNextBase();
			}
			
			else if(key.equals("EndTurn"))
			{
				
					//MainScreen.writeToConsole("PlayerKeyListener: End Turn", Color.BLUE);
					uim.endTurn();
			}
			
			else if(key.equals("UnitDoesNothing"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Unit Does Nothing", Color.BLUE);
				uim.unitDoesNothing();
			}
			
			else if(key.equals("BuildBase"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Build Base", Color.BLUE);
				uim.buildBase();
			}
			
			else if(key.equals("Attack"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Attack", Color.BLUE);
				uim.attack();
			}
			
			else if(key.equals("Sneak"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Sneak", Color.BLUE);
				uim.sneak();
			}
			
			else if(key.equals("Observe"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Observe", Color.BLUE);
				uim.observe();
			}
			
			else if(key.equals("RemoveTrap"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Detect & Remove Trap", Color.BLUE);
				uim.removeTrap();
			}
			
			else if(key.equals("SetTrap"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Set Trap", Color.BLUE);
				uim.setTrap();
			}
			
			else if(key.equals("PickupItem"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Pickup Item", Color.BLUE);
				uim.pickupItem();
			}
			
			else if(key.equals("DropItem"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Drop Item", Color.BLUE);
				uim.dropItem();
			}
			
			else if(key.equals("UseItem"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Use Item", Color.BLUE);
				uim.useItem();
			}
			
			else if(key.equals("HealUnit"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Heal Unit", Color.BLUE);
				uim.healUnit();
			}
			
			else if(key.equals("ToggleMission"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener:  Toggle Mission", Color.BLUE);
				uim.toggleMission();
			}
			
			else if(key.equals("ToggleFreeRoam"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener:  ");
				uim.toggleFreeRoam();
			}
			
			else if(key.equals("SetRallyPoint"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Set Rally Point", Color.BLUE);
				//TODO:  Figure out the commands for rally points
				//uim.startReceivingRallyPointCommands();
			}
			
			else if(key.equals("AssembleArmy"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Assemble Army", Color.BLUE);
				uim.assembleArmy();
			}
			
			else if(key.equals("DisbandArmy"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Disband Army", Color.BLUE);
				uim.disbandArmy();
			}
			
			else if(key.equals("AssembleBaseGroup"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Assemble Base Group", Color.BLUE);
				uim.assembleBaseGroup();
			}
			
			else if(key.equals("DisbandBaseGroup"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Disband Base Group", Color.BLUE);
				uim.disbandBaseGroup();
			}
			
			else if(key.equals("SelectResearchTech"))
			{
				//MainScreen.writeToConsole("PlayerKeyListener: Select Research Tech", Color.BLUE);
				uim.selectResearchTech();
			}
			else
			{
				//MainScreen.writeToConsole("KeyCode: " + KeyEvent.getKeyText(e.getKeyCode()));
			}
		}
	}
}
